
<!--
	作者：lsd
	时间：2020-4-15
	描述：采购员管理
-->
<template>
	<div class="m-view-purcheaserManager m-window">
    	<!-- 搜索头 -->
		<div class="m-condition">
			<el-row :gutter="5">
				<el-form
					:model="formSearch"
					ref="formSearch"
					label-width="70px"
					:inline-message="true"
					label-position="left"
				>
					<el-col :span="8">
						<el-form-item label="采购员" class="rightItem">
							<el-input
								value-key="id"
								v-model.trim="formSearch.searchKey"
								placeholder="请输入姓名/OA号/SAP号"
								clearable
								maxlength="20"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-checkbox @change="search(true)" v-model="formSearch.state">显示停用</el-checkbox>
					</el-col>
				</el-form>

				<el-col :span="2" :offset="4">
					<el-button type="primary" @click="search(true)">查询</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" @click="openPurcheaserDia(false)">新增</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" @click="openPurcheaserDia(true)">编辑</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" v-show="!formSearch.state" @click="isProhibit(0)">停用</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" v-show="formSearch.state" @click="isProhibit(0)">启用</el-button>
				</el-col>
			</el-row>
		</div>

    <!-- 表单 -->
		<div class="m-agTable m-bottom" v-loading="loading">
			<agGridComponents
				ref="agGridComponent"
				:getGridOptions="gridOptions"
				:getColumnDefs="columnDefs"
				:getRowSelection="'multiple'"
				:isColFit="true"
			></agGridComponents>
		</div>

    <!-- 页脚 -->
		<div class="m-page">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="pageInfo.currentPage"
				:page-sizes="[30,60,100,150,200 ]"
				:page-size="pageInfo.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
			></el-pagination>
		</div>

    	<!-- 新增&编辑窗口 -->
		<el-dialog
			:title="diaTittle"
			:visible.sync="diaPurcheaser"
			width="60"
			v-dialogDrag
			:before-close="closeDia"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<el-form
				:model="formPurcheaser"
				v-loading="loadingDia"
				ref="formPurcheaser"
				label-width="100px"
				class="demo-ruleForm"
				:rules="rules"
			>
				<el-form-item label="名字" prop="purcheaserName">
					<el-input v-model.trim="formPurcheaser.purcheaserName" placeholder="请填采购员名字" clearable maxlength="20" show-word-limit></el-input>
				</el-form-item>
				<el-form-item label="工号" prop="sapNum">
					<el-input v-model.trim="formPurcheaser.sapNum" placeholder="请填写其SAP号" clearable maxlength="20" show-word-limit></el-input>
				</el-form-item>
				<el-form-item label="OA号" prop="oaNum">
					<el-input v-model.trim="formPurcheaser.oaNum" placeholder="请填写其OA号" clearable maxlength="20" show-word-limit></el-input>
				</el-form-item>
			</el-form>

			<span slot="footer" class="dialog-footer">
				<el-button @click="closeDia">取消</el-button>
        <!-- 新增采购员 -->
				<el-button type="primary" v-show="!isEdit" @click="addPurcheaser(false)" :loading="loadingDia">保存</el-button>
				<el-button type="primary" v-show="!isEdit" @click="addPurcheaser(true)" :loading="loadingDia">保存并继续</el-button>
        <!-- 编辑采购员 -->
        <el-button type="primary" v-show="isEdit" @click="editPurcheaser(false)" :loading="loadingDia">保存</el-button>
				<!-- <el-button type="primary" v-show="isEdit" @click="editPurcheaser(true)" :loading="loadingDia">保存并继续</el-button> -->
			</span>
		</el-dialog>

  </div>
</template>
  
<script>
import agGridComponents from "@/components/agGridComponents.js";
import _Api from "@/api";
import localeText from "@/i18n/agGridText";

/**
 * @group purcheaserManager
 * 采购员管理
 */
export default {
	name: 'purcheaserManager',
	components:{
		agGridComponents,
	},
	data(){
		var checkOANum = (rule, value, callback) => {
			if (!value) {
				return callback(new Error('不能为空'));
			}
			else{ //没办法，你不套else肯定进不去表单验证
				if (this.OAList.indexOf(value) > -1) {
					if(this.isEdit && this.$refs.agGridComponent.gridOptions.api.getSelectedRows()[0].oaNum == value){ //如果是编辑就排除我自己
						return callback()
					}
					callback(new Error('该OA号已存在'));
				}
				return callback()
			}
			
		};
		var checkSAPNum = (rule, value, callback) => {
			if (!value) {
				return callback(new Error('不能为空'));
			}
			else{ //同上
				if (this.SAPList.indexOf(value) > -1) {
					if(this.isEdit && this.$refs.agGridComponent.gridOptions.api.getSelectedRows()[0].sapNum == value){ //如果是编辑就排除我自己
						return callback()
					}
					return callback(new Error('该工号已存在'));
				}
				return callback()
			}
		};
		return {
			formSearch:{//查询表
				searchKey: '',
				state: 0,
			},
			formPurcheaser:{ //新增&编辑采购员表
				purcheaserName: '',
				oaNum: '',
				sapNum: ''
			},
			isEdit: false,//true为编辑,false为新增
			rowData: [], // 表格数据
			OAList: [], //储存全部OA号
			SAPList: [],//存储全部SAP号
			//表格参数
			gridOptions: '',
			columnDefs: [],
			//页脚参数
			pageInfo: {
				pageSize: 30,
				currentPage: 1,
			},
			total: 0,
			//弹窗参数
			diaPurcheaser: false,//新增&编辑采购员弹框
			diaTittle: '',
			//加载参数
			loading: false,//页面的
			loadingDia: false,//弹框的
			rules: {
				purcheaserName: [{
					required: true,
					trigger: ['blur', 'change'],
					message: "不能为空",
				}],
				oaNum: [{
					required: true,
					validator: checkOANum,
					trigger: ['blur', 'change'],
				}],
				sapNum: [{
					required: true,
					validator: checkSAPNum,
					trigger: ['blur', 'change'],
				}]
			}
		}
	},
	beforeMount () {
		this.gridOptions = {
			context: {
				componentParent: this
			},
			enableColResize: true,
			localeText: localeText,
			suppressRowClickSelection: true,//单元格选中,false为选中整行
		};
		this.columnDefs = [
			{	headerName: "采购员", field: "purcheaserName", width: 130,
				checkboxSelection: true,
				headerCheckboxSelection: true			},
			{ headerName: "工号", field: "sapNum", width: 120 },
			{ headerName: "OA号", field: "oaNum", width: 120 },
			{				headerName: "状态", field: "state", width: 100,
				cellRenderer: (params) => {
					if (params.value == 0) {
						return '启用';
					} else {
						return '停用';
					}
				}
			},
			{ headerName: "创建人", field: "creator", width: 120 },
			{ headerName: "创建时间", field: "createDate", width: 150 },
			{ headerName: "修改人", field: "modifyer", width: 120 },
			{ headerName: "修改时间", field: "modifyDate", width: 150 },
		];

	},
	mounted(){
		this.search();
	},
	methods:{
		/**
		 * @vuese
		 * 查询方法
		 * 
		 * @arg 参数是布尔值， true就是点击触发，false就是非点击触发
		 */
		search(isClick){
			this.pageInfo.currentPage = isClick ? 1 : this.pageInfo.currentPage;
			this.loading = true;
			let param = {
				keyword: this.formSearch.searchKey,
				state: this.formSearch.state ? 1 : 0,
				...this.pageInfo,
			};
			_Api
				.searchPurcheaser(param)
				.then(res => {
					this.loading = false;
					if (res.data.code == 1) {
						this.rowData = res.data.rows;
						this.total = res.data.total
						this.$refs.agGridComponent.gridOptions.api.setRowData(this.rowData);
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loading = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},

		/**
		 * @vuese
		 * 新增采购员方法
		 * 
		 * @arg 
		 * isContinue表示是否继续，true为继续，false为不继续
		 */
		addPurcheaser(isContinue){
			this.$refs['formPurcheaser'].validate((valid) => {
				if (valid) {
					this.loadingDia = true;
					let param = this.formPurcheaser;
					_Api
						.addPurcheaser(param)
						.then(res => {
							this.loadingDia = false;
							if (res.data.code == 1) {
								this.$message({ message: "新增成功", type: "success" });
								this.search()//刷新数据
								this.clearParamter();//清空表单
								this.formPurcheaser.creatorId = this.$global.user.id;
								this.formPurcheaser.creator = this.$global.user.employeeName//创建人
								if (!isContinue) {//保存
									this.closeDia();
								}
							} else {
								this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
							}
						})
						.catch(err => {
							this.loadingDia = false;
							this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
						});
				}
			});
		},

		/**
		 * @vuese
		 * 编辑采购员方法
		 * 
		 * @arg  isContinue表示是否继续，true为继续，false为不继续
		 */
		editPurcheaser(isContinue = false){
			this.$refs['formPurcheaser'].validate((valid) => {
				if (valid) {
					this.loadingDia = true;
					let param = this.formPurcheaser;
					_Api
						.editPurcheaser(param)
						.then(res => {
							this.loadingDia = false;
							if (res.data.code == 1) {
								this.$message({ message: "编辑成功", type: "success" });
								if (!isContinue) {//保存并继续
									this.search()//刷新数据
									this.closeDia();
								}
							}else {
								this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
							}
						})
						.catch(err => {
							this.loadingDia = false;
							if(err.data.code == 0){
								this.$alert('OA号或者工号重复', { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
							}else{
								this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
							}
							
						});
				}
			});		
		},

		/**
		 * @vuese
		 * 停&启用采购员方法
		 */
		isProhibit(){
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
			if(row.length <= 0){
				this.$alert("提示：请至少选择一位采购员", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"					
				});
				return
			}

			let param = {
				ids: row.map(v=>v.id),
				modifyerId: this.$global.user.id,
				modifyer: this.$global.user.employeeName//修改人
			}
			this.$confirm(`是否${this.formSearch.state ? '启用' : '停用'}这些采购员`, "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(() => {
				this.loading = true;
				_Api
					.isProhibitPurchaser(param)
					.then(res => {
						this.loading = false;
						if (res.data.code == 1) {
							this.$message({
								message: `${this.formSearch.state ? '启用' : '停用'}成功！`,
								type: "success"
							});
							this.search();//刷新
						} else {
							this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
						}
					})
					.catch(err => {
						this.loading = false;
						this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					});
			})
		},

		/**
		 * @vuese
		 * 打开新增&编辑采购窗口方法
		 * 
		 * @arg 
		 * isEdit这个参数是布尔值，true表示为编辑窗口，false表示为新增窗口
		 */
		openPurcheaserDia( isEdit ){
			if(isEdit){//如果是编辑，初始化参数
				let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
				if(row.length != 1){
					this.$alert("提示：请选择一位采购员", {
							showClose: false,
							confirmButtonText: "确定",
							customClass: "alertPrompt"					
					});
					return
				}else{
					const {sapNum, oaNum, purcheaserName, state, id} = row[0];
					this.formPurcheaser = {sapNum, oaNum, purcheaserName, state, id};
					this.formPurcheaser.modifyerId = this.$global.user.id;
					this.formPurcheaser.modifyer = this.$global.user.employeeName//修改人
				}
			}else{
				this.formPurcheaser.creatorId = this.$global.user.id;
				this.formPurcheaser.creator = this.$global.user.employeeName//创建人
				this.formPurcheaser.state = 0;
			}

			this.diaTittle = `${isEdit?'编辑':'新增'}采购员`
			this.isEdit = isEdit;
			this.diaPurcheaser = true;
			this.getAllPurchaser();
		},
		
		/**
		 * @vuese
		 * 获取全部采购员信息
		 */
		getAllPurchaser(){
			this.loadingDia = true;
			_Api
				.getAllPurchaserList()
				.then(res => {
					this.loadingDia = false;
					if (res.data.code == 1) {
						let row = res.data.rows;
						this.OAList = row.map(v=>v.oaNum);
						this.SAPList = row.map(v=>v.sapNum);
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loadingDia = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},

		/**
		 * @vuese
		 * 改变页脚总条数方法
		 * 
		 * @arg 参数是 int 值，代表一页有多少条数据
		 */
		handleSizeChange (val) {
			this.pageInfo.pageSize = val;
			this.pageInfo.currentPage = 1;
			this.search();
		},

		/**
		 * @vuese
		 * 翻页方法
		 * 
		 * @arg 参数是 int 值，代表页数
		 */
		handleCurrentChange (val) {
			this.pageInfo.currentPage = val;
			this.search();
		},
		
		/**
		 * @vuese
		 * 清空参数方法
		 */
		clearParamter(){
			this.formPurcheaser = { 
				purcheaserName: '',
				oaNum: '',
				sapNum: ''
			}
			this.$refs.formPurcheaser.resetFields();
		},

		/**
		 * @vuese
		 * 关闭弹框方法
		 */
		closeDia() {
			this.diaPurcheaser = false;
			this.clearParamter();
		}
	}
}
</script>
  
